﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Mvc;
using System.Linq;
using Autofac;
using Autofac.Integration.Mvc;
using Freedom.Framework.Logging;
using Freedom.Framework.Mvc.Routes;

namespace Freedom.Framework.Mvc
{
    public class RegisterComponentConfig
    {

        public static ContainerBuilder GetBuilder()
        {
            var builder = new ContainerBuilder();

            var sumControllerDic = new Dictionary<string, Type>();
            foreach (var module in Utils.GetModuleInfo())
            {
                if (module.AssemblyFilePath == string.Empty) continue;

                byte[] buffer = File.ReadAllBytes(module.AssemblyFilePath);
                Assembly assembly = Assembly.Load(buffer);
                //register all the module assemblys
                //controller
                builder.RegisterAssemblyTypes(assembly).Where(
                    t =>
                    typeof (IController).IsAssignableFrom(t) && t.Name.EndsWith("Controller", StringComparison.Ordinal));

                //web api
                builder.RegisterAssemblyTypes(assembly).Where(
                    t =>
                    typeof (IHttpController).IsAssignableFrom(t) && t.Name.EndsWith("Controller", StringComparison.Ordinal));
                //route
                builder.RegisterAssemblyTypes(assembly).Where(t => t.Name.EndsWith("RouteProvider")).AsImplementedInterfaces().Keyed<IRouteProvider>(type => type.FullName.ToLower());

                //store the name-type in dictionary
                var controllerDic = assembly.GetTypes().Where(t => t.Name.EndsWith("Controller")).ToDictionary(t => t.FullName.ToLower());
                foreach (KeyValuePair<string, Type> controllerType in controllerDic)
                {
                    sumControllerDic.Add(controllerType.Key, controllerType.Value);
                }
            }

            //register the dictionary of stintg - controller type
            builder.RegisterInstance(sumControllerDic).Keyed<Dictionary<string, Type>>("ControllerDic");

            //register the log4net
            builder.Register(c => new Log4NetLogger()).As<ILogger>().InstancePerHttpRequest();
            builder.RegisterFilterProvider();

            return builder;
        }
    }
}
